package study.仪器解析.串口化通信.生化仪.监听COM1;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import study.仪器解析.串口化通信.生化仪.ASTMParser3;
import study.仪器解析.串口化通信.生化仪.entity.TotalRecord;

import java.util.List;

/**
 * @Author 刘伟涛
 * @Date 2024/8/28 13:29
 **/
public class 双向通信 {
    public static void main(String[] args) {
        // 打开串口
        SerialPort serialPort = SerialPort.getCommPort("COM3"); // 指定串口名称
        serialPort.setBaudRate(9600);
        serialPort.setNumDataBits(8);
        serialPort.setNumStopBits(SerialPort.ONE_STOP_BIT);
        serialPort.setParity(SerialPort.NO_PARITY);

        if (serialPort.openPort()) {
            System.out.println("串口打开成功！");
        } else {
            System.out.println("串口打开失败！");
            return;
        }

        // 监听接收数据
        serialPort.addDataListener(new SerialPortDataListener() {
            @Override
            public int getListeningEvents() {
                return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
            }

            @Override
            public void serialEvent(SerialPortEvent event) {
                if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
                    byte[] newData = new byte[serialPort.bytesAvailable()];
                    int numRead = serialPort.readBytes(newData, newData.length);
                    System.out.println("Received data: " + new String(newData));
                    ASTMParser3 astmParser = new ASTMParser3();
                    List<TotalRecord> totalRecords = astmParser.parseASTMMessage(new String(newData));
                    String dataToSend = ":01030000000AF2\r\n";
                    byte[] data = dataToSend.getBytes();
                    serialPort.writeBytes(data,data.length);
                }
            }
        });

/*        // 发送数据
        String dataToSend = ":01030000000AF2\r\n";
        byte[] data = dataToSend.getBytes();
        serialPort.writeBytes(data, data.length);
        System.out.println("Data sent: " + dataToSend);*/

        // 关闭串口
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (serialPort.closePort()) {
                System.out.println("串口关闭成功！");
            } else {
                System.out.println("串口关闭失败！");
            }
        }));
    }
}
